// USS FGUI 项目检查工具 - 优化输出版本
const fs = require('fs');
const path = require('path');

class USSCrossPackageChecker {
    constructor() {
        this.fguiProjectPath = "G:\\uss\\uss-art\\svn\\uss\\fgui";
        this.assetsPath = path.join(this.fguiProjectPath, 'assets');
        this.errors = [];
        this.warnings = [];
        this.info = [];
        this.oversizedImages = [];
        this.oversizedExportedImages = []; // 已导出的组件引用的大图
        this.oversizedOtherImages = []; // 其他大图
        this.oversizedAtlases = [];
        this.exportedResources = new Map(); // 存储所有导出的资源
        this.packageResources = new Map(); // 存储所有包的资源ID映射
        this.crossPackageRefs = []; // 存储跨包引用详细信息
        this.packageDependencies = new Map(); // 修复：初始化 packageDependencies
        this.debug = true; // 开启详细调试模式
        
        // 创建logs目录
        this.logsDir = path.join(__dirname, '..', 'logs');
        if (!fs.existsSync(this.logsDir)) {
            fs.mkdirSync(this.logsDir, { recursive: true });
        }
        
        // 生成日志文件名
        const timestamp = new Date().toISOString()
            .replace(/[:.]/g, '-')
            .replace('T', '_')
            .slice(0, -5);
        this.logFile = path.join(this.logsDir, `uss-cross-package-check-${timestamp}.log`);
        
        console.log('🎯 USS FGUI 项目检查工具 (优化输出版本)');
        console.log('====================================\n');
        console.log(`📁 日志文件: ${this.logFile}`);
    }

    // 日志记录
    log(message, type = 'info') {
        const timestamp = new Date().toLocaleString();
        const logMessage = `${message}`;
        
        if (type === 'error') {
            console.error('❌ ' + message);
        } else if (type === 'warning') {
            console.log('⚠️  ' + message);
        } else if (type === 'success') {
            console.log('✅ ' + message);
        } else if (type === 'detail') {
            console.log('📋 ' + message);
        } else {
            console.log('🔍 ' + message);
        }
        
        fs.appendFileSync(this.logFile, logMessage + '\n', 'utf8');
    }

    // 验证项目
    validateProject() {
        this.log('验证项目结构...');
        
        if (!fs.existsSync(this.fguiProjectPath)) {
            this.errors.push(`FGUI 项目路径不存在: ${this.fguiProjectPath}`);
            return false;
        }
        this.log(`项目路径: ${this.fguiProjectPath}`);

        const fairyFiles = fs.readdirSync(this.fguiProjectPath)
            .filter(file => file.endsWith('.fairy'));
            
        if (fairyFiles.length === 0) {
            this.errors.push('未找到 .fairy 项目文件');
            return false;
        }
        this.log(`项目文件: ${fairyFiles[0]}`, 'success');

        if (!fs.existsSync(this.assetsPath)) {
            this.errors.push('未找到 assets 目录');
            return false;
        }
        this.log('assets 目录存在', 'success');

        return true;
    }

    // 获取所有包
    getPackages() {
        if (!fs.existsSync(this.assetsPath)) return [];
        try {
            const items = fs.readdirSync(this.assetsPath);
            return items.filter(item => {
                const itemPath = path.join(this.assetsPath, item);
                return fs.statSync(itemPath).isDirectory();
            });
        } catch (error) {
            return [];
        }
    }

    // 1. 分析所有包的资源ID映射
    analyzePackageResources() {
        this.log('\n1. 分析各包资源ID映射...');
        
        const packages = this.getPackages();
        if (packages.length === 0) {
            this.errors.push('未找到任何包');
            return;
        }

        packages.forEach(pkg => {
            this.analyzePackageResourceIds(pkg);
        });

        // 输出资源统计
        let totalResources = 0;
        this.packageResources.forEach((resources, pkg) => {
            this.log(`包 "${pkg}" 有 ${resources.length} 个资源ID`, 'info');
            totalResources += resources.length;
        });

        this.log(`总计发现 ${totalResources} 个资源ID`, 'success');
    }

    // 分析单个包的资源ID映射
    analyzePackageResourceIds(pkg) {
        const pkgPath = path.join(this.assetsPath, pkg);
        const xmlFiles = this.findFilesDeep(pkgPath, '.xml');
        
        const resources = [];
        
        xmlFiles.forEach(xmlFile => {
            try {
                const content = fs.readFileSync(xmlFile, 'utf8');
                
                // 查找所有资源的ID映射
                const resourceItems = this.findResourceIds(content);
                resourceItems.forEach(item => {
                    resources.push({
                        type: item.type,
                        name: item.name,
                        id: item.id,
                        file: path.relative(pkgPath, xmlFile),
                        package: pkg
                    });
                });
                
            } catch (error) {
                this.errors.push(`无法分析资源ID: ${pkg}/${path.basename(xmlFile)}`);
            }
        });

        this.packageResources.set(pkg, resources);
    }

    // 查找所有资源的ID
    findResourceIds(xmlContent) {
        const resourceItems = [];
        
        // 查找所有组件 (component)
        const componentRegex = /<component[^>]*id="([^"]*)"[^>]*name="([^"]*)"[^>]*>/gi;
        let match;
        while ((match = componentRegex.exec(xmlContent)) !== null) {
            resourceItems.push({
                type: 'component',
                id: match[1],
                name: match[2]
            });
        }
        
        // 查找所有图片资源 (image)
        const imageRegex = /<image[^>]*id="([^"]*)"[^>]*name="([^"]*)"[^>]*>/gi;
        while ((match = imageRegex.exec(xmlContent)) !== null) {
            resourceItems.push({
                type: 'resource',
                id: match[1],
                name: match[2]
            });
        }
        
        return resourceItems;
    }

    // 2. 分析所有包的导出资源
    analyzeExportedResources() {
        this.log('\n2. 分析各包导出资源...');
        
        const packages = this.getPackages();
        if (packages.length === 0) {
            this.errors.push('未找到任何包');
            return;
        }

        packages.forEach(pkg => {
            this.analyzePackageExports(pkg);
        });

        // 输出导出资源统计
        let totalExported = 0;
        this.exportedResources.forEach((resources, pkg) => {
            this.log(`包 "${pkg}" 导出 ${resources.length} 个资源`, 'info');
            totalExported += resources.length;
        });

        this.log(`总计发现 ${totalExported} 个导出资源`, 'success');
    }

    // 分析单个包的导出资源
    analyzePackageExports(pkg) {
        const pkgPath = path.join(this.assetsPath, pkg);
        const xmlFiles = this.findFilesDeep(pkgPath, '.xml');
        
        const exported = [];
        
        xmlFiles.forEach(xmlFile => {
            try {
                const content = fs.readFileSync(xmlFile, 'utf8');
                
                // 查找所有导出的组件和图片资源
                const exportedItems = this.findExportedItems(content);
                exportedItems.forEach(item => {
                    exported.push({
                        type: item.type,
                        name: item.name,
                        id: item.id,
                        file: path.relative(pkgPath, xmlFile),
                        package: pkg
                    });
                });
                
            } catch (error) {
                this.errors.push(`无法分析导出资源: ${pkg}/${path.basename(xmlFile)}`);
            }
        });

        this.exportedResources.set(pkg, exported);
    }

    // 查找导出的组件和图片资源
    findExportedItems(xmlContent) {
        const exportedItems = [];
        
        // 更简单灵活的方法：先匹配所有导出的组件标签，再提取属性
        const componentRegex = /<component[^>]*exported="true"[^>]*>/gi;
        let match;
        while ((match = componentRegex.exec(xmlContent)) !== null) {
            const tag = match[0];
            const id = this.extractAttribute(tag, 'id');
            const name = this.extractAttribute(tag, 'name');
            const path = this.extractAttribute(tag, 'path');
            
            if (id && name) {
                exportedItems.push({
                    type: 'component',
                    id: id,
                    name: name,
                    path: path
                });
            }
        }

        // 同样的方法处理图片资源
        const imageRegex = /<image[^>]*exported="true"[^>]*>/gi;
        while ((match = imageRegex.exec(xmlContent)) !== null) {
            const tag = match[0];
            const id = this.extractAttribute(tag, 'id');
            const name = this.extractAttribute(tag, 'name');
            const path = this.extractAttribute(tag, 'path');
            
            if (id && name) {
                exportedItems.push({
                    type: 'resource',
                    id: id,
                    name: name,
                    path: path
                });
            }
        }
        
        return exportedItems;
    }

    // 3. 检查已导出组件内尺寸超过512px的图片
    checkOversizedSingleImages() {
        this.log('\n3. 检查已导出组件内尺寸超过512px的图片...');
        
        // 清空之前的记录
        this.oversizedExportedImages = [];
        this.oversizedOtherImages = [];
    
        const foundImages = new Set();
        const processedComponents = new Set();
        
        const packages = this.getPackages();
        
        packages.forEach(pkg => {
            const pkgPath = path.join(this.assetsPath, pkg);
            const packageXMLPath = path.join(pkgPath, 'package.xml');
            
            if (!fs.existsSync(packageXMLPath)) {
                this.log(`包 "${pkg}" 没有 package.xml 文件`, 'warning');
                return;
            }
            
            try {
                const packageContent = fs.readFileSync(packageXMLPath, 'utf8');
                const exportedComponents = this.findExportedComponentsInPackageXML(packageContent);
                
                this.log(`包 "${pkg}" 有 ${exportedComponents.length} 个导出组件`, 'info');
                
                // 特别调试：列出具体的导出组件
                exportedComponents.forEach(compId => {
                    this.log(`  导出组件ID: ${compId}`, 'debug');
                });
                
                if (exportedComponents.length === 0) {
                    this.log(`包 "${pkg}" 没有找到导出组件`, 'warning');
                    return;
                }
                
                exportedComponents.forEach(componentId => {
                    const componentFile = this.findComponentFileById(pkgPath, componentId);
                    if (componentFile) {
                        // this.log(`开始处理导出组件: ${path.relative(pkgPath, componentFile)} (ID: ${componentId})`, 'info');
                        if (!processedComponents.has(componentFile)) {
                            processedComponents.add(componentFile);
                            const callPath = [path.relative(pkgPath, componentFile)];
                            this.findImagesInExportedComponent(componentFile, pkgPath, foundImages, processedComponents, callPath);
                        }
                    } else {
                        this.log(`无法找到组件文件: ${componentId}`, 'warning');
                    }
                });
            } catch (error) {
                this.errors.push(`无法读取package.xml: ${pkg}/package.xml - ${error.message}`);
            }
        });
        
        // 输出结果...
    }

    // 在package.xml中查找导出的组件
// 在 findExportedComponentsInPackageXML 方法中添加调试
// 更严格的导出组件查找
findExportedComponentsInPackageXML(packageContent) {
    const exportedComponents = [];
    
    // 更严格的正则表达式，确保只匹配exported="true"
    const componentRegex = /<component\s+[^>]*?id="([^"]+)"[^>]*?exported="true"[^>]*?>/gi;
    let match;
    
    while ((match = componentRegex.exec(packageContent)) !== null) {
        const componentId = match[1];
        const fullTag = match[0];
        
        // 额外验证：确保exported属性确实是"true"
        const exportedMatch = /exported\s*=\s*"true"/i.exec(fullTag);
        if (exportedMatch) {
            // this.log(`确认导出组件: ID=${componentId}`, 'debug');
            exportedComponents.push(componentId);
        } else {
            this.log(`疑似导出但验证失败: ID=${componentId}`, 'warning');
        }
    }
    
    // 调试：列出所有组件及其导出状态
    const allComponentRegex = /<component\s+[^>]*?id="([^"]+)"[^>]*?>/gi;
    const allComponents = [];
    let allMatch;
    
    while ((allMatch = allComponentRegex.exec(packageContent)) !== null) {
        const compId = allMatch[1];
        const compTag = allMatch[0];
        const isExported = /exported\s*=\s*"true"/i.test(compTag);
        allComponents.push({id: compId, exported: isExported});
    }
    
    // this.log(`组件统计: 总计${allComponents.length}个, 导出${exportedComponents.length}个`, 'info');
    
    // 输出非导出组件的列表，用于调试
    const nonExported = allComponents.filter(comp => !comp.exported);
    if (nonExported.length > 0) {
        // this.log(`非导出组件: ${nonExported.map(comp => comp.id).join(', ')}`, 'debug');
    }
    
    return exportedComponents;
}
    // 根据组件ID查找组件文件
    findComponentFileById(pkgPath, componentId) {
        const xmlFiles = this.findFilesDeep(pkgPath, '.xml');
        
        for (const xmlFile of xmlFiles) {
            try {
                const content = fs.readFileSync(xmlFile, 'utf8');
                // 查找匹配ID的组件定义
                const componentRegex = new RegExp(`<component[^>]*id="${componentId}"[^>]*>`, 'i');
                if (componentRegex.test(content)) {
                    return xmlFile;
                }
            } catch (error) {
                this.log(`读取组件文件失败: ${xmlFile}`, 'warning');
            }
        }
        
        return null;
    }

    // 在递归开始时验证组件导出状态
findImagesInExportedComponent(componentFile, pkgPath, foundImages, processedComponents, callPath, depth = 0) {
    if (depth > 10) return;
    
    try {
        const content = fs.readFileSync(componentFile, 'utf8');
        const baseDir = path.dirname(componentFile);
        const relativePath = path.relative(pkgPath, componentFile);
        
        // 验证当前组件是否确实导出（深度防御）
        if (depth === 0) {
            const componentId = this.extractComponentIdFromFile(content);
            if (componentId && !this.isComponentExported(pkgPath, componentId)) {
                // this.log(`错误: 尝试处理非导出组件 ${relativePath} (ID: ${componentId})`, 'error');
                return;
            }
        }
        
        // this.log(`分析组件: ${relativePath} (深度: ${depth})`, 'detail');
        
        // 原有逻辑...
        this.findDirectImagesInComponent(content, pkgPath, foundImages, baseDir, callPath);
        this.findLoaderImagesInComponent(content, pkgPath, foundImages, baseDir, callPath);
        this.findSubComponentsInComponent(content, pkgPath, foundImages, processedComponents, baseDir, depth, callPath);
        
    } catch (error) {
        this.errors.push(`无法读取组件文件: ${componentFile} - ${error.message}`);
    }
}

// 新增方法：从组件文件内容中提取组件ID
extractComponentIdFromFile(xmlContent) {
    const componentRegex = /<component[^>]*id="([^"]*)"[^>]*>/i;
    const match = componentRegex.exec(xmlContent);
    return match ? match[1] : null;
}

// 新增方法：验证组件是否导出
isComponentExported(pkgPath, componentId) {
    const packageXMLPath = path.join(pkgPath, 'package.xml');
    if (!fs.existsSync(packageXMLPath)) {
        return false;
    }
    
    try {
        const content = fs.readFileSync(packageXMLPath, 'utf8');
        const exportedRegex = new RegExp(`<component[^>]*id="${componentId}"[^>]*exported="true"[^>]*>`, 'i');
        return exportedRegex.test(content);
    } catch (error) {
        this.log(`检查组件导出状态失败: ${componentId} - ${error.message}`, 'warning');
        return false;
    }
}

    // 查找组件中直接引用的图片
    findDirectImagesInComponent(xmlContent, pkgPath, foundImages, baseDir, callPath) {
        // 查找image标签 - 同时处理fileName和src属性
        const imageRegex = /<image[^>]*?(?:fileName="([^"]*)"|src="([^"]*)")[^>]*>/gi;
        let match;
        
        while ((match = imageRegex.exec(xmlContent)) !== null) {
            const fileName = match[1];
            const srcId = match[2];
            
            // this.log(`在组件 ${callPath[callPath.length - 1]} 中找到图片引用: fileName=${fileName}, srcId=${srcId}`, 'detail');
            
            // 优先处理src属性（资源ID引用）
            if (srcId) {
                // 通过资源ID查找对应的图片文件
                const imageFileFromSrc = this.findImageFileByResourceId(pkgPath, srcId);
                if (imageFileFromSrc) {
                    this.checkAndAddImage(imageFileFromSrc, pkgPath, foundImages, baseDir, callPath);
                    continue;
                } else {
                    // 如果通过src找不到，记录警告
                    // this.log(`无法通过src找到图片: ${srcId}`, 'warning');
                }
            }
            
            // 处理fileName属性
            if (fileName) {
                this.checkAndAddImage(fileName, pkgPath, foundImages, baseDir, callPath);
            }
        }
        
        // 同时查找其他可能的图片引用格式
        const otherImageRefs = this.extractOtherImageReferences(xmlContent);
        if (otherImageRefs.length > 0) {
            // this.log(`在组件 ${callPath[callPath.length - 1]} 中找到其他图片引用: ${otherImageRefs.join(', ')}`, 'detail');
        }
        otherImageRefs.forEach(fileName => {
            this.checkAndAddImage(fileName, pkgPath, foundImages, baseDir, callPath);
        });
    }

    // 增强通过资源ID查找图片文件的方法
    findImageFileByResourceId(pkgPath, resourceId) {
        const pkgName = path.basename(pkgPath);
        const resources = this.packageResources.get(pkgName) || [];
        
        // this.log(`查找资源ID: ${resourceId} 在包: ${pkgName}`, 'detail');
        
        // 查找匹配的资源
        const resource = resources.find(r => r.id === resourceId);
        if (resource && resource.type === 'resource') {
            // this.log(`找到资源定义: ${resource.name}`, 'detail');
            
            // 首先尝试从package.xml获取精确路径
            const imagePath = this.findImagePathInPackageXML(pkgPath, resourceId);
            if (imagePath) {
                return imagePath;
            }
            
            // 如果无法从package.xml获取，尝试各种可能的路径
            const possiblePaths = [
                // 尝试默认image目录
                path.join(pkgPath, 'image', resource.name),
                // 尝试根目录
                path.join(pkgPath, resource.name),
                // 尝试带扩展名的路径
                path.join(pkgPath, 'image', resource.name + '.png'),
                path.join(pkgPath, 'image', resource.name + '.jpg'),
                path.join(pkgPath, 'image', resource.name + '.jpeg'),
                path.join(pkgPath, resource.name + '.png'),
                path.join(pkgPath, resource.name + '.jpg'),
                path.join(pkgPath, resource.name + '.jpeg')
            ];
            
            for (const possiblePath of possiblePaths) {
                if (fs.existsSync(possiblePath)) {
                    return possiblePath;
                }
            }
            
            // 如果还找不到，在整个包内搜索文件名
            this.log(`在整个包内搜索文件: ${resource.name}`, 'detail');
            const allImages = this.findFilesDeep(pkgPath, ['.png', '.jpg', '.jpeg']);
            for (const imageFile of allImages) {
                const fileName = path.basename(imageFile, path.extname(imageFile));
                if (fileName === resource.name) {
                    return imageFile;
                }
            }
            
            this.log(`无法找到资源ID ${resourceId} 对应的图片文件`, 'warning');
        } else {
            // this.log(`未找到资源ID: ${resourceId} 或不是图片资源`, 'warning');
        }
        
        return null;
    }

    // 增强从package.xml中查找资源路径的方法
    findImagePathInPackageXML(pkgPath, resourceId) {
        const packageXMLPath = path.join(pkgPath, 'package.xml');
        if (!fs.existsSync(packageXMLPath)) {
            return null;
        }
        
        try {
            const content = fs.readFileSync(packageXMLPath, 'utf8');
            
            // 使用更灵活的正则表达式匹配image标签
            const resourceRegex = new RegExp(`<image[^>]*id="${resourceId}"[^>]*>`, 'i');
            const match = resourceRegex.exec(content);
            
            if (match) {
                // 提取name和path属性
                const nameMatch = /name="([^"]*)"/i.exec(match[0]);
                const pathMatch = /path="([^"]*)"/i.exec(match[0]);
                
                if (nameMatch) {
                    const name = nameMatch[1];
                    let resourcePath = pathMatch ? pathMatch[1] : '';
                    
                    // 处理路径格式
                    if (resourcePath.startsWith('/')) {
                        resourcePath = resourcePath.substring(1);
                    }
                    if (resourcePath.endsWith('/')) {
                        resourcePath = resourcePath.substring(0, resourcePath.length - 1);
                    }
                    
                    // 构建完整路径
                    let fullPath;
                    if (resourcePath) {
                        fullPath = path.join(pkgPath, resourcePath, name);
                    } else {
                        fullPath = path.join(pkgPath, name);
                    }
                    
                    // 确保路径存在
                    if (fs.existsSync(fullPath)) {
                        return fullPath;
                    }
                    
                    // 如果直接路径不存在，尝试添加扩展名
                    if (!fullPath.toLowerCase().endsWith('.png') && 
                        !fullPath.toLowerCase().endsWith('.jpg') && 
                        !fullPath.toLowerCase().endsWith('.jpeg')) {
                        
                        const extensions = ['.png', '.jpg', '.jpeg'];
                        for (const ext of extensions) {
                            const pathWithExt = fullPath + ext;
                            if (fs.existsSync(pathWithExt)) {
                                return pathWithExt;
                            }
                        }
                    }
                    
                    // 如果还找不到，尝试在image目录下查找
                    const imageDirPath = path.join(pkgPath, 'image', name);
                    if (fs.existsSync(imageDirPath)) {
                        return imageDirPath;
                    }
                    
                    // 尝试添加扩展名在image目录下
                    for (const ext of ['.png', '.jpg', '.jpeg']) {
                        const imageDirPathWithExt = path.join(pkgPath, 'image', name + ext);
                        if (fs.existsSync(imageDirPathWithExt)) {
                            return imageDirPathWithExt;
                        }
                    }
                }
            } else {
                this.log(`在package.xml中未找到资源ID: ${resourceId}`, 'warning');
            }
        } catch (error) {
            this.log(`读取package.xml失败: ${error.message}`, 'warning');
        }
        
        return null;
    }

    // 提取其他可能的图片引用
    extractOtherImageReferences(xmlContent) {
        const refs = [];
        
        // 查找可能包含图片路径的属性
        const patterns = [
            /url="([^"]*\.(png|jpg|jpeg))"/gi,
            /file="([^"]*\.(png|jpg|jpeg))"/gi,
            /texture="([^"]*\.(png|jpg|jpeg))"/gi
        ];
        
        patterns.forEach(pattern => {
            let match;
            while ((match = pattern.exec(xmlContent)) !== null) {
                refs.push(match[1]);
            }
        });
        
        return refs;
    }

    // 查找组件中loader引用的图片（没有clearOnPublish属性的）
    findLoaderImagesInComponent(xmlContent, pkgPath, foundImages, baseDir, callPath) {
        // 查找loader标签，且没有clearOnPublish属性
        const loaderRegex = /<loader(?!.*clearOnPublish[^>]*)[^>]*url="([^"]*)"[^>]*>/gi;
        let match;
        
        while ((match = loaderRegex.exec(xmlContent)) !== null) {
            const url = match[1];
            this.log(`在组件 ${callPath[callPath.length - 1]} 中找到loader引用: ${url}`, 'detail');
            
            // 检查是否是ui://格式的跨包引用
            if (url.startsWith('ui://')) {
                // 解析ui://包名/资源名
                const parts = url.substring(5).split('/');
                if (parts.length === 2) {
                    const [targetPkg, resourceName] = parts;
                    
                    // 查找目标包中对应的图片文件
                    const targetPkgPath = path.join(this.assetsPath, targetPkg);
                    if (fs.existsSync(targetPkgPath)) {
                        // 查找目标包中匹配资源名的图片文件
                        const imageFiles = this.findFilesDeep(targetPkgPath, ['.png', '.jpg', '.jpeg']);
                        for (const imageFile of imageFiles) {
                            const fileName = path.basename(imageFile);
                            if (fileName === resourceName || fileName === resourceName + '.png') {
                                this.checkAndAddImage(imageFile, targetPkgPath, foundImages, path.dirname(imageFile), callPath);
                                break;
                            }
                        }
                    }
                }
            } else {
                // 处理普通URL
                this.checkAndAddImage(url, pkgPath, foundImages, baseDir, callPath);
            }
        }
    }

    // 查找子组件
    // 修复子组件查找逻辑，只处理导出组件的子组件
findSubComponentsInComponent(xmlContent, pkgPath, foundImages, processedComponents, baseDir, depth, callPath) {
    const componentRefs = this.extractComponentReferences(xmlContent);
    
    if (componentRefs.length > 0) {
        // this.log(`在组件 ${callPath[callPath.length - 1]} 中找到 ${componentRefs.length} 个子组件引用`, 'detail');
    }
    
    componentRefs.forEach(ref => {
        let subComponentFile = null;
        
        if (ref.type === 'src') {
            subComponentFile = this.findComponentFileById(pkgPath, ref.value);
        } else if (ref.type === 'name') {
            subComponentFile = this.findComponentFileByName(pkgPath, ref.value, baseDir);
        }
        
        if (subComponentFile && !processedComponents.has(subComponentFile)) {
            // 深度防御：即使子组件也要验证导出状态（可选，根据需求）
            // 如果只需要直接导出的组件，可以注释掉这部分
            /*
            const subComponentId = this.extractComponentIdFromFile(fs.readFileSync(subComponentFile, 'utf8'));
            if (subComponentId && !this.isComponentExported(pkgPath, subComponentId)) {
                this.log(`跳过非导出子组件: ${ref.value}`, 'detail');
                return;
            }
            */
            
            processedComponents.add(subComponentFile);
            const newCallPath = [...callPath, path.relative(pkgPath, subComponentFile)];
            this.findImagesInExportedComponent(subComponentFile, pkgPath, foundImages, processedComponents, newCallPath, depth + 1);
        }
    });
}

    // 提取组件引用（包括src和name）
    extractComponentReferences(xmlContent) {
        const refs = [];
        
        // 1. 查找通过src属性引用的组件
        const srcRegex = /<component[^>]*src="([^"]*)"[^>]*>/gi;
        let match;
        while ((match = srcRegex.exec(xmlContent)) !== null) {
            refs.push({
                type: 'src',
                value: match[1]
            });
        }
        
        // 2. 查找通过name引用的组件
        const componentRefRegex = /<component[^>]*name="([^"]*\.xml)"[^>]*>/gi;
        while ((match = componentRefRegex.exec(xmlContent)) !== null) {
            refs.push({
                type: 'name',
                value: match[1]
            });
        }
        
        return refs;
    }

    // 根据组件名称查找组件文件
    findComponentFileByName(pkgPath, componentName, baseDir) {
        // 首先在相同目录下查找
        let componentFile = path.join(baseDir, componentName);
        if (fs.existsSync(componentFile)) {
            return componentFile;
        }
        
        // 如果找不到，在整个包内查找
        const xmlFiles = this.findFilesDeep(pkgPath, '.xml');
        for (const xmlFile of xmlFiles) {
            const fileName = path.basename(xmlFile);
            if (fileName === componentName) {
                return xmlFile;
            }
        }
        
        return null;
    }

    // 检查图片尺寸并添加到结果
    checkAndAddImage(fileName, pkgPath, foundImages, baseDir, callPath) {
        if (!fileName) return;
        
        // this.log(`检查图片: ${fileName}`, 'detail');
        
        const imagePath = this.resolveImagePath(fileName, pkgPath, baseDir);
        
        if (!imagePath) {
            this.log(`无法解析图片路径: ${fileName}`, 'warning');
            return;
        }
        
        if (foundImages.has(imagePath)) {
            this.log(`图片已处理过: ${imagePath}`, 'detail');
            return;
        }
        
        try {
            const dimensions = this.estimateImageDimensions(imagePath);
            if (dimensions) {
                // this.log(`图片尺寸: ${imagePath} - ${dimensions.width}x${dimensions.height}`, 'detail');
                if (dimensions.width > 512 || dimensions.height > 512) {
                    const relativePath = path.relative(this.assetsPath, imagePath);
                    const imageInfo = {
                        path: relativePath,
                        width: dimensions.width,
                        height: dimensions.height,
                        size: `${dimensions.width}x${dimensions.height}`,
                        package: path.relative(this.assetsPath, pkgPath),
                        callPath: [...callPath] // 保存调用路径
                    };
                    this.oversizedExportedImages.push(imageInfo);
                    foundImages.add(imagePath);
                    
                    this.log(`发现大图: ${relativePath} (${dimensions.width}x${dimensions.height})`, 'warning');
                }
            } else {
                this.log(`无法获取图片尺寸: ${imagePath}`, 'warning');
            }
        } catch (error) {
            this.log(`检查图片尺寸失败: ${imagePath} - ${error.message}`, 'warning');
        }
    }

    // 增强路径解析方法
    resolveImagePath(fileName, pkgPath, baseDir) {
        // this.log(`解析图片路径: ${fileName}, baseDir: ${baseDir}, pkgPath: ${pkgPath}`, 'detail');
        
        // 如果已经是完整路径且存在
        if (fs.existsSync(fileName)) {
            // this.log(`使用完整路径: ${fileName}`, 'detail');
            return fileName;
        }
        
        // 尝试在基础目录下查找
        let imagePath = path.join(baseDir, fileName);
        if (fs.existsSync(imagePath)) {
            // this.log(`使用基础目录路径: ${imagePath}`, 'detail');
            return imagePath;
        }
        
        // 尝试在包根目录下查找
        imagePath = path.join(pkgPath, fileName);
        if (fs.existsSync(imagePath)) {
            // this.log(`使用包根目录路径: ${imagePath}`, 'detail');
            return imagePath;
        }
        
        // 尝试处理可能的相对路径
        if (fileName.startsWith('../') || fileName.startsWith('./')) {
            imagePath = path.resolve(baseDir, fileName);
            if (fs.existsSync(imagePath)) {
                // this.log(`使用相对路径解析: ${imagePath}`, 'detail');
                return imagePath;
            }
        }
        
        // 尝试在image目录下查找
        imagePath = path.join(pkgPath, 'image', fileName);
        if (fs.existsSync(imagePath)) {
            // this.log(`使用image目录路径: ${imagePath}`, 'detail');
            return imagePath;
        }
        
        // 如果fileName已经是相对路径，尝试直接拼接
        imagePath = path.join(pkgPath, fileName);
        if (fs.existsSync(imagePath)) {
            // this.log(`使用直接拼接路径: ${imagePath}`, 'detail');
            return imagePath;
        }
        
        this.log(`无法解析图片路径: ${fileName}`, 'warning');
        return null;
    }

    // 增强图片尺寸估计方法
    estimateImageDimensions(imagePath) {
        if (!fs.existsSync(imagePath)) {
            this.log(`图片文件不存在: ${imagePath}`, 'warning');
            return null;
        }
        
        try {
            const buffer = fs.readFileSync(imagePath);
            
            // 对于PNG文件
            if (imagePath.toLowerCase().endsWith('.png')) {
                if (buffer.readUInt32BE(0) === 0x89504E47) {
                    const width = buffer.readUInt32BE(16);
                    const height = buffer.readUInt32BE(20);
                    // this.log(`PNG图片尺寸: ${imagePath} - ${width}x${height}`, 'detail');
                    return { width, height };
                }
            }
            
            // 对于JPEG文件
            if (imagePath.toLowerCase().endsWith('.jpg') || imagePath.toLowerCase().endsWith('.jpeg')) {
                if (buffer.readUInt16BE(0) === 0xFFD8) {
                    // JPEG文件，需要解析SOF标记
                    let offset = 2;
                    while (offset < buffer.length - 1) {
                        const marker = buffer.readUInt16BE(offset);
                        // SOF0, SOF1, SOF2 等标记
                        if (marker >= 0xFFC0 && marker <= 0xFFCF && marker !== 0xFFC4 && marker !== 0xFFC8) {
                            // 找到SOF标记
                            const height = buffer.readUInt16BE(offset + 5);
                            const width = buffer.readUInt16BE(offset + 7);
                            // this.log(`JPEG图片尺寸: ${imagePath} - ${width}x${height}`, 'detail');
                            return { width, height };
                        }
                        const segmentLength = buffer.readUInt16BE(offset + 2);
                        if (segmentLength < 2) break;
                        offset += 2 + segmentLength;
                    }
                }
            }
            
            this.log(`无法识别图片格式或获取尺寸: ${imagePath}`, 'warning');
        } catch (error) {
            this.log(`读取图片文件失败: ${imagePath} - ${error.message}`, 'warning');
        }
        
        return null;
    }

    // 4. 检查图集尺寸和数量
    checkAtlasSizeAndCount() {
        this.log('\n4. 检查图集尺寸和数量...');
        
        const packages = this.getPackages();
        let atlasIssues = 0;

        packages.forEach(pkg => {
            const pkgPath = path.join(this.assetsPath, pkg);
            const atlasFiles = this.findAtlasFiles(pkgPath);
            
            if (atlasFiles.length > 0) {
                this.log(`包 "${pkg}" 有 ${atlasFiles.length} 个图集`);
                
                // 检查图集数量
                if (atlasFiles.length > 2) {
                    const largeAtlases = [];
                    atlasFiles.forEach(atlasFile => {
                        try {
                            const dimensions = this.estimateImageDimensions(atlasFile);
                            if (dimensions && (dimensions.width > 2048 || dimensions.height > 2048)) {
                                const relativePath = path.relative(this.assetsPath, atlasFile);
                                largeAtlases.push({
                                    path: relativePath,
                                    width: dimensions.width,
                                    height: dimensions.height,
                                    size: `${dimensions.width}x${dimensions.height}`
                                });
                            }
                        } catch (error) {
                            // 忽略错误
                        }
                    });

                    this.oversizedAtlases.push({
                        package: pkg,
                        atlasCount: atlasFiles.length,
                        largeAtlases: largeAtlases
                    });
                    atlasIssues++;
                    
                    this.warnings.push(`包 "${pkg}" 有 ${atlasFiles.length} 个图集，建议优化`);
                }
            }
        });

        if (atlasIssues === 0) {
            this.log('图集数量和尺寸检查通过', 'success');
        } else {
            this.log(`发现 ${atlasIssues} 个包的图集数量问题`, 'warning');
        }

        return atlasIssues;
    }

    // 5. 深度检查资源引用（支持跨包引用）
    checkResourceReferencesWithCrossPackage() {
        this.log('\n5. 检查资源引用（支持跨包引用）...');
        
        const packages = this.getPackages();
        if (packages.length === 0) {
            this.errors.push('未找到任何包');
            return;
        }

        let totalMissingRefs = 0;

        packages.forEach(pkg => {
            const pkgPath = path.join(this.assetsPath, pkg);
            const xmlFiles = this.findFilesDeep(pkgPath, '.xml');
            
            let packageMissingRefs = 0;
            
            xmlFiles.forEach(xmlFile => {
                const missingInThisFile = this.checkXMLReferencesCrossPackage(pkg, xmlFile);
                packageMissingRefs += missingInThisFile;
            });

            if (packageMissingRefs === 0) {
                this.log(`包 "${pkg}" 资源引用完整`, 'success');
            } else {
                this.log(`包 "${pkg}" 有 ${packageMissingRefs} 个缺失引用`, 'warning');
                totalMissingRefs += packageMissingRefs;
            }
        });

        if (totalMissingRefs === 0) {
            this.log('所有资源引用检查通过', 'success');
        } else {
            this.log(`总计发现 ${totalMissingRefs} 个缺失引用`, 'error');
        }
    }

    // 检查 XML 引用（支持跨包）
    checkXMLReferencesCrossPackage(currentPkg, xmlFile) {
        let missingRefs = 0;
        
        try {
            const content = fs.readFileSync(xmlFile, 'utf8');
            const relativePath = path.relative(path.join(this.assetsPath, currentPkg), xmlFile);
            
            // 提取所有资源引用（src属性）
            const srcRefs = this.extractSrcReferences(content);
            
            srcRefs.forEach(src => {
                if (!this.findReferencedResource(currentPkg, src)) {
                    this.errors.push(`资源引用不存在: ${currentPkg}/${relativePath} -> ${src}`);
                    missingRefs++;
                }
            });
            
        } catch (error) {
            this.errors.push(`无法读取 XML: ${currentPkg}/${path.basename(xmlFile)}`);
        }
        
        return missingRefs;
    }

    // 提取src引用
    extractSrcReferences(xmlContent) {
        const refs = [];
        
        // 提取所有src属性的值
        const srcRegex = /src="([^"]*)"/gi;
        let match;
        while ((match = srcRegex.exec(xmlContent)) !== null) {
            const ref = match[1];
            if (ref && ref.trim() !== '') {
                refs.push(ref);
            }
        }
        
        return [...new Set(refs)];
    }

    // 查找引用的资源（支持跨包）
    findReferencedResource(currentPkg, src) {
        // 1. 首先在当前包内查找是否有匹配id的资源
        const currentPkgResources = this.packageResources.get(currentPkg) || [];
        const inCurrentPackage = currentPkgResources.some(resource => 
            resource.id === src
        );
        
        if (inCurrentPackage) {
            return true;
        }
        
        // 2. 在其他包的导出资源中查找
        for (const [pkg, resources] of this.exportedResources) {
            if (pkg === currentPkg) continue; // 跳过当前包
            
            const exportedResource = resources.find(resource => resource.id === src);
            
            if (exportedResource) {
                // 记录跨包引用关系
                if (!this.packageDependencies.has(currentPkg)) {
                    this.packageDependencies.set(currentPkg, new Set());
                }
                this.packageDependencies.get(currentPkg).add(pkg);
                
                // 记录详细的跨包引用信息
                this.crossPackageRefs.push({
                    sourcePackage: currentPkg,
                    targetPackage: pkg,
                    resourceId: src,
                    resourceName: exportedResource.name,
                    resourceType: exportedResource.type
                });
                
                return true;
            }
        }
        
        // 3. 如果都找不到，返回false
        return false;
    }

    // 6. 检查包依赖关系
    checkPackageDependencies() {
        this.log('\n6. 检查包依赖关系...');
        
        if (!this.packageDependencies || this.packageDependencies.size === 0) {
            this.log('未发现跨包依赖关系', 'info');
            return;
        }

        // 按源包分组跨包引用
        const crossPackageBySource = {};
        this.crossPackageRefs.forEach(ref => {
            if (!crossPackageBySource[ref.sourcePackage]) {
                crossPackageBySource[ref.sourcePackage] = {};
            }
            if (!crossPackageBySource[ref.sourcePackage][ref.targetPackage]) {
                crossPackageBySource[ref.sourcePackage][ref.targetPackage] = [];
            }
            crossPackageBySource[ref.sourcePackage][ref.targetPackage].push(ref);
        });

        // 输出跨包引用（排除Common和NoCompression包）
        let hasCrossPackageOutput = false;
        
        Object.keys(crossPackageBySource).forEach(sourcePkg => {
            const targetPackages = crossPackageBySource[sourcePkg];
            
            Object.keys(targetPackages).forEach(targetPkg => {
                // 排除Common和NoCompression包
                if (targetPkg === 'Common' || targetPkg === 'NoCompression') {
                    return;
                }
                
                if (!hasCrossPackageOutput) {
                    this.log('跨包引用:');
                    hasCrossPackageOutput = true;
                }
                
                this.log(`  ${sourcePkg} -> ${targetPkg}`);
                
                // 输出该包对的所有资源引用
                targetPackages[targetPkg].forEach(ref => {
                    const typeLabel = ref.resourceType === 'component' ? '组件' : '图片';
                    this.log(`                ${sourcePkg} -> ${targetPkg} (资源id: ${ref.resourceId}, ${typeLabel}: ${ref.resourceName})`);
                });
            });
        });

        if (!hasCrossPackageOutput) {
            this.log('未发现跨包依赖关系（除Common和NoCompression外）', 'info');
        }

        // 检查循环依赖
        let hasCircularDependency = false;
        const dependencyChains = [];
        
        if (this.packageDependencies) {
            this.packageDependencies.forEach((deps, pkg) => {
                const depList = Array.from(deps).join(', ');
                
                // 检查循环依赖
                deps.forEach(depPkg => {
                    if (this.packageDependencies.has(depPkg) && 
                        this.packageDependencies.get(depPkg).has(pkg)) {
                        this.warnings.push(`循环依赖: ${pkg} <-> ${depPkg}`);
                        hasCircularDependency = true;
                    }
                    
                    // 记录依赖链
                    dependencyChains.push(`${pkg} -> ${depPkg}`);
                });
            });
        }

        if (!hasCircularDependency) {
            this.log('依赖关系正常，无循环依赖', 'success');
        } else {
            this.log('发现循环依赖，建议优化', 'warning');
        }

        // 输出依赖链信息
        if (dependencyChains.length > 0) {
            this.info.push('依赖链: ' + dependencyChains.join('; '));
        }
    }

    // 工具函数
    findAtlasFiles(pkgPath) {
        const allImages = this.findFilesDeep(pkgPath, ['.png', '.jpg', '.jpeg']);
        return allImages.filter(imageFile => {
            const filename = path.basename(imageFile).toLowerCase();
            return filename.startsWith('atlas') || 
                   /atlas\d+\./.test(filename) ||
                   filename.includes('texture');
        });
    }

    findFilesDeep(dir, extensions) {
        if (!fs.existsSync(dir)) return [];
        const results = [];
        const items = fs.readdirSync(dir);
        const exts = extensions ? (Array.isArray(extensions) ? extensions : [extensions]) : null;

        items.forEach(item => {
            if (item.startsWith('.') || item === 'Thumbs.db') return;
            const fullPath = path.join(dir, item);
            try {
                const stat = fs.statSync(fullPath);
                if (stat.isDirectory()) {
                    results.push(...this.findFilesDeep(fullPath, exts));
                } else if (exts === null) {
                    results.push(fullPath);
                } else {
                    const ext = path.extname(item).toLowerCase();
                    if (exts.includes(ext)) {
                        results.push(fullPath);
                    }
                }
            } catch (error) {
                // 忽略错误
            }
        });
        return results;
    }

    // 添加辅助方法：从标签字符串中提取属性值
    extractAttribute(tagString, attributeName) {
        const regex = new RegExp(`${attributeName}="([^"]*)"`, 'i');
        const match = tagString.match(regex);
        return match ? match[1] : '';
    }

    // 生成详细报告
    generateReport() {
        const reportContent = [];
        
        reportContent.push('='.repeat(70));
        reportContent.push('        USS FGUI 项目检查报告 (优化输出版本)');
        reportContent.push('='.repeat(70));
        reportContent.push(`检查时间: ${new Date().toLocaleString()}`);
        reportContent.push(`项目路径: ${this.fguiProjectPath}`);
        reportContent.push(`日志文件: ${this.logFile}`);
        reportContent.push('');

        // 项目统计
        const packages = this.getPackages();
        const allImages = this.findFilesDeep(this.assetsPath, ['.png', '.jpg', '.jpeg']);
        const allXMLs = this.findFilesDeep(this.assetsPath, '.xml');
        const allFonts = this.findFilesDeep(this.assetsPath, ['.fnt', '.ttf', '.otf']);

        reportContent.push('📊 项目统计:');
        reportContent.push(`   包数量: ${packages.length}`);
        reportContent.push(`   图片文件: ${allImages.length}`);
        reportContent.push(`   XML 文件: ${allXMLs.length}`);
        reportContent.push(`   字体文件: ${allFonts.length}`);
        
        // 导出资源统计
        let totalExported = 0;
        this.exportedResources.forEach((resources, pkg) => {
            totalExported += resources.length;
        });
        reportContent.push(`   导出资源: ${totalExported}`);
        reportContent.push('');

        // 依赖关系统计
        if (this.packageDependencies && this.packageDependencies.size > 0) {
            reportContent.push('🔗 依赖关系:');
            this.packageDependencies.forEach((deps, pkg) => {
                reportContent.push(`   ${pkg} -> ${Array.from(deps).join(', ')}`);
            });
            reportContent.push('');
        }

        // 单图尺寸检查结果 - 只显示已导出组件引用的大图
        if (this.oversizedExportedImages.length > 0) {
            reportContent.push('📏 单图尺寸检查（超过512px）:');
            reportContent.push(`   已导出的组件引用大于512尺寸的图（${this.oversizedExportedImages.length}个）:`);
            
            // 按包分组显示
            const imagesByPackage = {};
            this.oversizedExportedImages.forEach(img => {
                if (!imagesByPackage[img.package]) {
                    imagesByPackage[img.package] = [];
                }
                imagesByPackage[img.package].push(img);
            });
            
            Object.keys(imagesByPackage).forEach(pkg => {
                reportContent.push(`     包 "${pkg}" (${imagesByPackage[pkg].length}个):`);
                imagesByPackage[pkg].forEach(img => {
                    const callPathInfo = img.callPath ? ` [引用路径: ${img.callPath.join(' -> ')}]` : '';
                    reportContent.push(`       ${img.path} (${img.size})${callPathInfo}`);
                });
            });
            reportContent.push('');
        } else {
            reportContent.push('📏 单图尺寸检查:');
            reportContent.push('   未发现已导出的组件引用大于512尺寸的图');
            reportContent.push('');
        }

        // 图集检查结果
        if (this.oversizedAtlases.length > 0) {
            reportContent.push('🖼️  图集数量检查（超过2个2048图集）:');
            this.oversizedAtlases.forEach(atlasInfo => {
                reportContent.push(`   包 "${atlasInfo.package}" 有 ${atlasInfo.atlasCount} 个图集`);
            });
            reportContent.push('');
        }

        // 输出错误
        if (this.errors.length > 0) {
            reportContent.push('❌ 错误:');
            this.errors.forEach(error => reportContent.push(`   ${error}`));
            reportContent.push('');
        }

        // 输出警告
        if (this.warnings.length > 0) {
            reportContent.push('⚠️  警告:');
            this.warnings.forEach(warning => reportContent.push(`   ${warning}`));
            reportContent.push('');
        }

        // 输出信息（跨包引用等）
        if (this.info.length > 0) {
            reportContent.push('ℹ️  信息:');
            this.info.forEach(info => reportContent.push(`   ${info}`));
            reportContent.push('');
        }

        // 优化建议
        if (this.warnings.length > 0 || this.oversizedAtlases.length > 0 || 
            (this.packageDependencies && this.packageDependencies.size > 0)) {
            reportContent.push('💡 优化建议:');
            
            if (this.oversizedExportedImages.length > 0) {
                reportContent.push('   1. 单图尺寸超过512px，建议压缩或拆分');
            }
            
            if (this.oversizedAtlases.length > 0) {
                reportContent.push('   2. 图集数量过多，建议在FGUI编辑器中优化图集设置');
            }
            
            if (this.packageDependencies && this.packageDependencies.size > 0) {
                reportContent.push('   3. 跨包依赖较多，考虑将常用资源放到公共包中');
            }
            
            if (this.warnings.some(w => w.includes('循环依赖'))) {
                reportContent.push('   4. 发现循环依赖，需要重构包结构');
            }
            
            reportContent.push('   5. 定期运行检查工具，确保资源引用完整性');
            reportContent.push('');
        }

        // 总结
        reportContent.push('='.repeat(70));
        reportContent.push(`错误: ${this.errors.length}, 警告: ${this.warnings.length}`);
        reportContent.push(`超大单图: ${this.oversizedExportedImages.length} (仅检查导出的组件引用)`);
        reportContent.push(`图集问题: ${this.oversizedAtlases.length}`);
        if (this.packageDependencies) {
            reportContent.push(`跨包依赖: ${this.packageDependencies.size} 个包有外部依赖`);
        } else {
            reportContent.push(`跨包依赖: 0 个包有外部依赖`);
        }

        let conclusion = '';
        if (this.errors.length > 0) {
            conclusion = '❌ 检查失败，请修复错误！';
        } else if (this.warnings.length > 0) {
            conclusion = '⚠️  检查完成，有警告需要注意';
        } else {
            conclusion = '✅ 所有检查通过！USS FGUI 项目状态良好';
        }
        reportContent.push(conclusion);
        reportContent.push('='.repeat(70));

        // 输出到控制台和日志
        reportContent.forEach(line => {
            if (line.includes('❌')) {
                this.log(line.replace('❌ ', ''), 'error');
            } else if (line.includes('⚠️')) {
                this.log(line.replace('⚠️ ', ''), 'warning');
            } else if (line.includes('✅')) {
                this.log(line.replace('✅ ', ''), 'success');
            } else if (line.includes('📊') || line.includes('🔗') || line.includes('📏') || line.includes('🖼️') || line.includes('💡') || line.includes('ℹ️')) {
                console.log(line);
            } else if (line.startsWith('=')) {
                console.log(line);
            } else if (line.trim()) {
                console.log(line);
            }
        });

        const fullReport = reportContent.join('\n');
        fs.appendFileSync(this.logFile, '\n' + fullReport + '\n', 'utf8');

        return {
            errors: this.errors.length,
            warnings: this.warnings.length,
            oversizedExportedImages: this.oversizedExportedImages.length,
            oversizedOtherImages: this.oversizedOtherImages.length,
            oversizedAtlases: this.oversizedAtlases.length,
            crossPackageDependencies: this.packageDependencies ? this.packageDependencies.size : 0,
            logFile: this.logFile
        };
    }

    // 运行检查
    run() {
        this.log('🚀 开始 USS FGUI 项目检查 (优化输出版本)...');
        this.log(`检查开始时间: ${new Date().toLocaleString()}`);
        
        if (!this.validateProject()) {
            this.generateReport();
            return;
        }

        // 执行检查（注意顺序）
        this.analyzePackageResources();            // 先分析所有包的资源ID映射
        this.analyzeExportedResources();           // 分析导出资源
        this.checkOversizedSingleImages();         // 检查单图尺寸（仅检查导出的组件引用）
        this.checkAtlasSizeAndCount();             // 检查图集
        this.checkResourceReferencesWithCrossPackage(); // 检查资源引用（支持跨包）
        this.checkPackageDependencies();           // 检查包依赖关系
        
        const result = this.generateReport();
        
        this.log(`检查完成时间: ${new Date().toLocaleString()}`);
        this.log(`详细报告已保存: ${result.logFile}`);
        
        if (result.errors > 0) {
            process.exit(1);
        } else {
            process.exit(0);
        }
    }
}

// 运行检查
if (require.main === module) {
    const checker = new USSCrossPackageChecker();
    checker.run();
}

module.exports = USSCrossPackageChecker;